package xyz.zhzby.cyzx.cms.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import io.swagger.annotations.ApiOperation;
import xyz.zhzby.cyzx.cms.entity.ArticleTag;
import xyz.zhzby.cyzx.cms.mapper.ArticleTagMapper;
import xyz.zhzby.cyzx.cms.service.IArticleTagService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import xyz.zhzby.cyzx.security.entity.User;
import xyz.zhzby.cyzx.security.util.CyzxSecurityContextHolder;
import xyz.zhzby.cyzx.servicebase.domain.DataLogInfo;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 文章与文章标签关联表 服务实现类
 * </p>
 *
 * @author zby
 * @since 2021-12-10
 */
@Service
public class ArticleTagServiceImpl extends ServiceImpl<ArticleTagMapper, ArticleTag> implements IArticleTagService {

    @Override
    public void linkArticleTag(Long id, List<Long> tagIds) {
        removeByArticleId(id);

        User subject = CyzxSecurityContextHolder.getSubject();
        for (Long tagId : tagIds) {
            ArticleTag articleTag = new ArticleTag();
            articleTag.setArticleId(id);
            articleTag.setTagId(tagId);
            subject.fillCreateInfo(articleTag, DataLogInfo.USER_FIELD_ACTUAL_NAME);
            baseMapper.insert(articleTag);
        }
    }

    @ApiOperation("根据文章ID删除关联")
    private void removeByArticleId(Long articleId) {
        LambdaQueryWrapper<ArticleTag> qw = new LambdaQueryWrapper<>();
        qw.eq(ArticleTag::getArticleId, articleId);
        baseMapper.delete(qw);
    }

    @Override
    public List<Long> getArticleIdsByTagId(Long tagID) {
        LambdaQueryWrapper<ArticleTag> qw = new LambdaQueryWrapper<>();
        qw.eq(ArticleTag::getTagId, tagID);
        qw.select(ArticleTag::getArticleId);
        List<ArticleTag> articleTags = baseMapper.selectList(qw);
        return articleTags.stream().map(ArticleTag::getArticleId).collect(Collectors.toList());
    }
}
